package com.guigu.controller;

import com.google.gson.Gson;
import com.guigu.pojo.Member;
import com.guigu.pojo.Sfz;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class SfzController {
    @PostMapping("/sfz")
    public Sfz show(@RequestBody Member identity) throws IOException {
        String url = "https://eid.shumaidata.com/eid/check";
        String appCode = "cf388fe4141242368c0d26a7186b4a19";
        Map<String, String> params = new HashMap<>();
        params.put("idcard", identity.getIdcard());
        params.put("name", identity.getName());
        String result = postForm(appCode, url, params);
        System.out.println(result);
        Gson gson = new Gson();
        Sfz sfz = gson.fromJson(result, Sfz.class);

        System.out.println(sfz);
        return sfz;

    }
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }
}
